package com.dekarrin.util;

/**
 * Wraps Strings to a specified length.
 */
public class StringWrapper {

	/**
	 * The maximum length of a line.
	 */
	private int lineWidth;
	
	/**
	 * What to separate each line with.
	 */
	private String lineBreak;
	
	/**
	 * Creates a new StringWrapper.
	 *
	 * @param lineWidth
	 * The maximum length of a line.
	 *
	 * @param lineBreak
	 * What to separate each line with.
	 */
	public StringWrapper(int lineWidth, String lineBreak) {
		this.lineWidth = lineWidth;
		this.lineBreak = lineBreak;
	}
	
	/**
	 * Wraps text. Credit to Minimum length wrap pseudocode on Wikipedia for
	 * algorithm <http://en.wikipedia.org/wiki/Word_wrap#Algorithm>.
	 *
	 * @param text
	 * The text to wrap.
	 *
	 * @return
	 * The wrapped text.
	 */
	public String wrap(String text) {
		StringBuilder wrappedText = new StringBuilder();
		int spaceLeft = lineWidth;
		String[] textWords = text.split(" ");
		int spaceLength = 0;
		for (String word: textWords) {
			if ((word.length() + spaceLength) > spaceLeft) {
				wrappedText.append(lineBreak);
				spaceLeft = lineWidth - word.length();
			} else {
				if (spaceLength != 0) {
					wrappedText.append(" ");
				}
				spaceLeft -= (word.length() + spaceLength);
			}
			wrappedText.append(word);
			spaceLength = 1;
		}
		return wrappedText.toString();
	}

}